﻿using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Pear.Application.LiveCenter.Dtos;
using Pear.Application.UserCenter.Common;
using Pear.Core;
using Pear.Core.Entities.LiveCenter;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pear.Application.LiveCenter.LiveServices
{

    /// <summary>
    /// 设备服务
    /// </summary>
    [ApiDescriptionSettings(ApiGroupConsts.LiveCenter)]
    [AllowAnonymous]
    public class DeviceAppService : IDynamicApiController, ITransient
    {

        //1.构造函数注入
        SqlSugar.ISqlSugarClient _db;
        public DeviceAppService(ISqlSugarClient db)
        {

            this._db = db;
        }

        /// <summary>
        /// 获取所有用户列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_LIST), HttpGet, ApiDescriptionSettings(Name = "list")]
        public async Task<PagedList<DeviceModel>> GetListAsync([FromQuery, Required] BaseListInput input)
        {
            var hasKeyword = !string.IsNullOrEmpty(input.Keyword?.Trim());

            var devices = _db.Queryable<DeviceModel>().ToPagedList(input.PageIndex, input.PageSize);

            return devices.Adapt<PagedList<DeviceModel>>();
        }

        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_PROFILE_SELF), HttpGet]
        public DeviceModel Profile(string deviceCode)
        {
            var model = _db.Queryable<DeviceModel>().Where(q => q.Code == deviceCode).First();
            if (model == null)
            {
                throw Oops.Oh("无效的设备,请联系管理员添加设备");
            }
            if (!model.Enabled)
            {
                throw Oops.Oh("设备未激活,请联系管理员激活设备");
            }
            return model;
        }


        /// <summary>
        /// 新增 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_ADD), ApiDescriptionSettings(KeepVerb = true)]
        public async Task<DeviceModel> AddAsync([Required] AddDeviceInput input)
        {
            var model = input.Adapt<DeviceModel>();
            model.CreateTime = DateTime.Now;
            model.Id = await _db.Insertable<DeviceModel>(model).ExecuteReturnBigIdentityAsync();
            if (model.Id > 0)
            {
                model = _db.Queryable<DeviceModel>().InSingle(model.Id);
                return model;
            }
            throw new NotImplementedException("添加失败");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="videoIds"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_DELETE), HttpDelete]
        public async Task DeleteAsync([Required, MinLength(1), MaxLength(20), FromBody] int[] deviceIds)
        {
            // 判断用户Id中是否有重复项
            var isRepeat = deviceIds.GroupBy(i => i).Any(g => g.Count() > 1);
            if (isRepeat) throw Oops.Oh(SystemErrorCodes.u1011);

            if (_db.Deleteable<DeviceModel>(deviceIds).ExecuteCommand() <= 0)
            {
                throw Oops.Oh("删除失败");
            }
        }

        /// <summary>
        /// 编辑信息
        /// </summary> 
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_MODIFY), HttpPut]
        public async Task<DeviceModel> ModifyAsync([Required] ModifyDeviceInput input)
        {
            if (input.Id <= 0)
            {
                throw new NotImplementedException("无效的视频信息");
            }
            var model = input.Adapt<DeviceModel>();
            model.UpdateTime = DateTime.Now;
            var row = await _db.Updateable<DeviceModel>(model).IgnoreColumns(q => q.CreateTime).ExecuteCommandAsync();
            if (row > 0)
            {
                model = _db.Queryable<DeviceModel>().InSingle(model.Id);
                return model;
            }
            throw new NotImplementedException("修改失败");
        }



        /// <summary>
        /// 修改视频VideoUrl信息
        /// </summary> 
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine(SecurityConsts.USER_SERVICE_MODIFY), HttpPost]
        public async Task<bool> ModifyVideoUrlAsync([Required] ModifyDeviceVideoUrlInput input)
        {
            if (string.IsNullOrWhiteSpace(input.VideoUrl))
            {
                throw new NotImplementedException("无效的视频信息");
            }
            var row = await _db.Updateable<DeviceModel>()
                .SetColumns(it => it.VideoUrl == input.VideoUrl)
                .Where(q => q.Code == input.Code)
                .ExecuteCommandAsync();
            if (row > 0)
            {
                return true;
            }
            throw new NotImplementedException("修改失败");
        }

    }
}
